import React, { CSSProperties } from 'react';
import { ColumnProps } from 'antd/lib/table';
import { Form, Button, Select, DatePicker } from 'antd';
import _ from 'lodash';
import { StateType } from '@/common-typings';
import styles from './style.less';
import { checkPermission } from '@/utils/resolvePermission';
import { USER_TYPE, ORDER_TYPE_DETAIL, REPORT_TRANSFER_STATUS } from './data';
import * as tools from '@/utils/tools';

const { Option } = Select;

const getExportBtn = (rowData: any, btnText: any = '') => (
  <div className={styles.tabelBtns}>
    {rowData.detailPath ? (
      <button type="button">
        <a href={rowData.detailPath}>{`导出${btnText}明细`}</a>
      </button>
    ) : null}
  </div>
);

export const toTrans = (arr: any[], val: number) => {
  const obj = _.find(arr, item => item.value === val);
  return obj ? obj.title : '';
};

// 表格标题
export const getColumns = (
  self: any,
  total: any = '充值总额',
  count: any = '充值笔数',
  dataIndex = 'totalRechargeAmount',
) => {
  const columns: ColumnProps<StateType>[] = [
    {
      width: '14.2%',
      title: '日期',
      dataIndex: 'date',
    },
    {
      width: '14.2%',
      title: '商户名称',
      dataIndex: 'channelName',
      render: (text: any, rowData: any) => {
        if (text === '全部商户') {
          return <strong style={{ color: 'red' }}>{text}</strong>;
        }
        return text;
      },
    },
    {
      width: '14.2%',
      title: '商户号',
      dataIndex: 'merchantCode',
    },
    {
      width: '14.2%',
      title: total,
      dataIndex,
    },
    {
      width: '14.2%',
      title: count,
      dataIndex: 'totalRow',
    },
    {
      width: '14.2%',
      title: '商户手续费总额',
      dataIndex: 'totalFeeAmount',
    },

    {
      width: '14.2%',
      title: '操作',
      key: 'tags',
      render: (text: any, rowData: any, index: any) => {
        if (
          rowData.channelName === '全部商户' &&
          checkPermission(self.props.btns, self.allExportPermission)
        ) {
          return getExportBtn(rowData, '全部');
        }
        if (
          rowData.channelName !== '全部商户' &&
          checkPermission(self.props.btns, self.exportPermission)
        ) {
          return getExportBtn(rowData);
        }
        return null;
      },
    },
  ];
  return columns;
};

// 搜索表单
export const ReportForm = (props: any) => {
  const { getFieldDecorator, handleSubmit, resetForm, merchantList, onDateChange } = props;
  const newMerchantList = JSON.parse(JSON.stringify(merchantList));
  const delItem: any = newMerchantList.splice(0, 1);
  if (delItem[0]) {
    newMerchantList.unshift(delItem[0], {
      channelId: -2,
      channelName: '人工出款',
    });
  }

  return (
    <Form layout="inline" onSubmit={handleSubmit} name="searchRecharge">
      <Form.Item label="日期">
        {getFieldDecorator('date', {})(
          <DatePicker showToday format="YYYY-MM-DD" onChange={onDateChange} />,
        )}
      </Form.Item>

      <Form.Item label="商户名称：" style={{ width: '275px' }}>
        {getFieldDecorator('channelId', {
          initialValue: '-1',
        })(
          <Select style={{ width: '200px' }} placeholder="请选择商户名称">
            {newMerchantList.map((ele: any, index: any) => (
              <Option key={ele.channelName} value={ele.channelId}>
                {ele.channelName}
              </Option>
            ))}
          </Select>,
        )}
      </Form.Item>

      <Form.Item className={styles.footer}>
        <Button type="primary" htmlType="submit">
          查询
        </Button>
        <Button onClick={resetForm}>重置</Button>
        {/* <Button>导出</Button> */}
      </Form.Item>
    </Form>
  );
};

export const WithdrawReportForm = (props: any) => {
  const { getFieldDecorator, handleSubmit, resetForm, merchantList } = props;
  if (merchantList instanceof Array) {
    merchantList.unshift({
      channelId: -2,
      channelName: '人工出款',
    });
  }

  return (
    <Form layout="inline" onSubmit={handleSubmit} name="searchRecharge">
      <Form.Item label="日期">
        {getFieldDecorator('date', {})(<DatePicker showToday format="YYYY-MM-DD" />)}
      </Form.Item>

      <Form.Item label="商户名称：" style={{ width: '275px' }}>
        {getFieldDecorator('channelId', {
          initialValue: '-1',
        })(
          <Select style={{ width: '200px' }} placeholder="请选择商户名称">
            {merchantList.map((ele: any, index: any) => (
              <Option key={ele.channelName} value={ele.channelId}>
                {ele.channelName}
              </Option>
            ))}
          </Select>,
        )}
      </Form.Item>

      <Form.Item className={styles.footer}>
        <Button type="primary" htmlType="submit">
          查询
        </Button>
        <Button onClick={resetForm}>重置</Button>
        {/* <Button>导出</Button> */}
      </Form.Item>
    </Form>
  );
};

export const TableFooter = (props: any): any => {
  const { total } = props;
  return (
    <table className={styles.reportTableFooter}>
      <tbody className="ant-table-tbody">
        <tr className="ant-table-row ant-table-row-level-0">
          <td>合计：</td>
          <td> </td>
          <td></td>
          <td>{total.totalAmount} </td>
          <td>{total.totalRow}</td>
          <td> {total.totalFee}</td>
          <td> </td>
        </tr>
      </tbody>
    </table>
  );
};

export function getTransationColumns(tableFilters?: any, getColumnSearchProps?: any) {
  const greenTextStyle: CSSProperties = {
    color: '#97C586',
  };
  const orangeTextStyle: CSSProperties = {
    color: '#FFA427',
  };
  const redTextStyle: CSSProperties = {
    color: '#FF1314',
  };
  let userTypeData;
  let statusData;

  if (tableFilters) {
    const { userType, status } = tableFilters;
    userTypeData = userType ? [userType] : ['-1'];
    statusData = status ? [status] : ['-1'];
  }

  const columns: ColumnProps<StateType>[] = [
    {
      title: '交易订单号',
      dataIndex: 'orderId',
      width: 230,
    },
    {
      title: '账户名',
      dataIndex: 'username',
      width: 90,
    },
    {
      title: '账户类型',
      dataIndex: 'userType',
      width: 120,
      render: text => toTrans(USER_TYPE, text),
      filters: [
        { text: '全部', value: '-1' },
        { text: '会员', value: '0' },
        { text: '代理', value: '1' },
      ],
      filteredValue: userTypeData,
      filterMultiple: false,
    },
    {
      title: '所属代理',
      dataIndex: 'parentName',
      width: 90,
      ...getColumnSearchProps('parentName'),
    },
    {
      title: '交易类型',
      dataIndex: 'orderType',
      width: 90,
      render: text => toTrans(ORDER_TYPE_DETAIL, text.toString()),
    },
    {
      title: '细分类型',
      dataIndex: 'subType',
      width: 90,
      render: text => text || '-',
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
      render: text => tools.toTime(text),
      width: 100,
      sorter: (a, b) => a.createTime - b.createTime,
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      width: 130,
      render: text => tools.currency(text),
    },
    {
      title: '手续费',
      dataIndex: 'fee',
      width: 130,
      render: text => tools.currency(text),
    },
    {
      title: '应到账',
      dataIndex: 'reallyAmount',
      width: 130,
      render: text => tools.currency(text),
    },
    {
      title: '中心钱包帐变前余额',
      dataIndex: 'balanceBefore',
      width: 140,
      render: (text, record) => {
        const val = record.status === 0 && record.orderType !== 2 ? '-' : tools.currency(text);
        return val;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: text => {
        let style;
        if (text === 1) {
          style = greenTextStyle;
        } else if (text === 0) {
          style = orangeTextStyle;
        } else if (text === 2) {
          style = redTextStyle;
        }
        return <span style={style}>{toTrans(REPORT_TRANSFER_STATUS, text)}</span>;
      },
      filters: [
        { text: '全部', value: '-1' },
        { text: '处理中', value: '0' },
        { text: '成功', value: '1' },
        { text: '失败', value: '2' },
      ],
      filteredValue: statusData,
      filterMultiple: false,
    },
    {
      title: '中心钱包帐变后余额',
      dataIndex: 'balance',
      width: 140,
      render: (text, record) => {
        const val = record.status === 0 && record.orderType !== 2 ? '-' : tools.currency(text);
        return val;
      },
    },
    {
      title: '帐变时间',
      dataIndex: 'finishTime',
      width: 100,
      render: text => tools.toTime(text),
    },
  ];
  return columns;
}

export const formatObj = {
  userType: (val: any) => toTrans(USER_TYPE, val),
  orderType: (val: any) => toTrans(ORDER_TYPE_DETAIL, val.toString()),
  createTime: (val: any) => tools.toTime(val),
  amount: (val: any) => tools.currency(val),
  fee: (val: any) => tools.currency(val),
  reallyAmount: (val: any) => tools.currency(val),
  balanceBefore: (val: any, record: any) => {
    const value = record.status === 0 && record.orderType !== 2 ? '' : tools.currency(val);
    return value;
  },
  status: (val: any) => toTrans(REPORT_TRANSFER_STATUS, val),
  balance: (val: any, record: any) => {
    const value = record.status === 0 && record.orderType !== 2 ? '' : tools.currency(val);
    return value;
  },
  finishTime: (val: any) => tools.toTime(val),
};

export function checkHasChanged(tableFilters: object, filters: object): boolean {
  let flag = false;
  const filtersKeys = Object.keys(filters);
  _.forEach(filtersKeys, item => {
    const filtersItemValue = filters[item].join(',');
    if (filtersItemValue !== tableFilters[item]) {
      flag = true;
    }
  });
  return flag;
}
